package com.huaxin.hxcloud.service;

import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.huaxin.common.AppManager;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.AppVersionDTO;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.cache.DiskCache;
import com.huaxin.common.tools.AppOperator;
import com.huaxin.common.tools.Log;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LocationService extends Service {
    private final static String TAG = "LocationService";
    private final static int LOCATION = 0x991;
    private final static int GETWARNING = LOCATION + 1;
    private final static int SETROUTE = LOCATION + 2;
    private final static int UPDATE = LOCATION + 3;




    private LatLng latLng;


    public LocationClient mLocationClient = null;

    private final BDLocationListener myListener = new MyLocationListener();

    private static double BAIDU_MAP_LOCATION_DEFAULT = 4.9E-324D;

    /**
     * 上次定位开始时间
     */
//    private long startTime = 0;

    private Vibrator vibrator;

    String updateUrl;

//    int needUpdate;

    IBinder myBinder = new MyBinder();


    @Override
    public IBinder onBind(Intent arg0) {
        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startLocation();
//        ApiCheckUpdate();

    }

    private void startLocation() {
        if(mLocationClient==null){
            mLocationClient = new LocationClient(LocationService.this); // 声明LocationClient类
            mLocationClient.registerLocationListener(myListener); // 注册监听函数
        }
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(1000 * Constants.scanSpan);
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值gcj02
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    private void ApiCheckUpdate() {
        Call<AppVersionDTO> call =  RequestHelper.getRequestApi().checkUpdate(this.getVersionName(),0);
        call.enqueue(new Callback<AppVersionDTO>() {
            @Override
            public void onResponse(Call<AppVersionDTO> call, Response<AppVersionDTO> response) {
                AppVersionDTO appVersionDTO = response.body();
                if(response.isSuccessful()&&appVersionDTO!=null){
                    if(appVersionDTO.isSuccessful()){
                        updateUrl = appVersionDTO.getFileName();
//                        String  version = appVersionDTO.getVersion();
//                        if (Float.valueOf(version) > Float.valueOf(BuildConfig.VERSION_CODE)){
//                            checkUpdate();
                        showUpdateDialog(AppManager.getAppManager().currentActivity(), updateUrl);
//                        }

                    }
                }
            }

            @Override
            public void onFailure(Call<AppVersionDTO> call, Throwable t) {

            }
        });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        handle.removeMessages(LOCATION);
        handle.removeMessages(UPDATE);
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(myListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        vibrator.cancel();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || location.getLatitude() == BAIDU_MAP_LOCATION_DEFAULT
                    || location.getLatitude() == BAIDU_MAP_LOCATION_DEFAULT)
                return;
            LatLng temp = new LatLng(location.getLatitude(), location.getLongitude());
            double distance = DistanceUtil.getDistance(latLng, temp);
            if(distance!=-1&&distance>10){
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                ApiCommitLngLat();
            }
        }



        public void onReceivePoi(BDLocation poiLocation) {
            // 将在下个版本中去除poi功能
            if (poiLocation == null) {
                return;
            }
        }
    }
    private void ApiCommitLngLat() {
        Call<BaseDTO> call = RequestHelper.getRequestApi().commitLngLat(latLng.longitude,latLng.latitude);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                if(response.isSuccessful()&&baseDTO!=null){
                    if(baseDTO.isSuccessful()){
                        Log.i(TAG,"LngLat:"+ latLng.longitude+","+latLng.latitude);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {

            }
        });

    }

    private Handler handle = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case LOCATION:
                    if (mLocationClient == null) {
                        mLocationClient = new LocationClient(LocationService.this); // 声明LocationClient类
                        mLocationClient.registerLocationListener(myListener); // 注册监听函数
                    }
                    LocationClientOption option = new LocationClientOption();
                    option.setScanSpan(1000 * Constants.scanSpan);
                    option.setOpenGps(true);// 打开gps
                    option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值gcj02
                    mLocationClient.setLocOption(option);
                    mLocationClient.start();
                    break;
                default:
                    break;
            }
            return false;
        }
    });



    /*
     * 获取当前程序的版本号
     */
    private String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        String version = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            version = packInfo.versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return version;
    }

    public class MyBinder extends Binder {
        public LatLng getLocation() {
            return latLng;
        }

    }


    /*
     *
     * 弹出对话框通知用户更新程序
     */
    public static void showUpdateDialog(final Context context, final String url) {
        if(context==null){
            return;
        }
        Dialog dialog = DialogUtil.getConfirmDialog(context, "检测到新版本，是否升级",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ToastUtil.showToast( "后台开始下载,请您稍等");
                        downLoadApk(context, url);
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ToastUtil.showToast( "您可以到设置界面手动更新");
                    }
                }).create();
        dialog.show();
    }

    /*
         * 从服务器中下载APK
         */
    private static void downLoadApk(final Context context, final String url) {
        AppOperator.runOnThread(new Runnable() {
            @Override
            public void run() {
                if(downLoadApp(url))  {
                    installApk(context);
                }else{
                    ToastUtil.showToast("更新包下载失败");
                }

            }
        });
    }


    private static boolean downLoadApp(String url){
        boolean ret = false;
        Call<ResponseBody> call = RequestHelper.getRequestApi().downloadFile(url);
        Response<ResponseBody> response = null;
        try {
            response = call.execute();
            if(response.isSuccessful()){
                ret =  DiskCache.putInputStream(Constants.APP_NAME, response.body().byteStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
            ret =  false;
        }
        return ret;
    }

    // 安装apk
    private static void installApk(final Context context) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(DiskCache.getFile(Constants.APP_NAME)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}
